# -*- coding: utf-8 -*-
import cgi
import os 
import datetime
import time
import wsgiref.handlers
import string

from control import *
from time import strftime, localtime 
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from loginTool import login_required
from regUserInit import addInitReplay

class User(db.Model): #//用户表 
  userName = db.StringProperty(multiline=True) #//用户名
  passWord = db.StringProperty(multiline=True)  #//密码
  trueName = db.StringProperty(multiline=True)  #//姓名
  tele = db.StringProperty(multiline=True)      #//电话号码
  mobile = db.StringProperty(multiline=True)    #//手机
  date = db.DateTimeProperty(auto_now_add=True)  #//注册时间

class PublicPage(webapp.RequestHandler):
  def render(self, template_file, template_value):
      path = os.path.join(os.path.dirname(__file__), template_file)
      self.response.out.write(template.render(path, template_value))

class UserInfo(PublicPage):
  @login_required
  def get(self):
    searchType = self.request.get('searchType')
#    template_values = {'searchType':searchType,}
    self.redirect("/userList/0?searchType=%s" %searchType)
#    self.render('template/user/userList.html',template_values)
    #self.render('html/userManage/userList.html',template_values)

class UserList(PublicPage):
  @login_required
  def get(self,page):
    searchType = self.request.get('searchType')#'searchType‘不存在是返回的不是None，而是''空字符
    if searchType=='userName':
      greetings = db.GqlQuery("SELECT * "
                              "FROM User "
                              "ORDER BY %s DESC LIMIT 100" %searchType)
    else:
      if searchType=='date':
        greetings = db.GqlQuery("SELECT * "
                                "FROM User "
                                "ORDER BY %s DESC LIMIT 100" %searchType)
      else:
        if searchType=='':
          greetings = db.GqlQuery("SELECT * "
                                  "FROM User "
                                  "ORDER BY userName,date DESC LIMIT 100")
        else:
          greetings = db.GqlQuery("SELECT * FROM User WHERE userName=:1",searchType)

    index=0 if page=="" else int(page)
    greetings = greetings.fetch(16,index*16)
    prev,next=getPageing(len(greetings), index)
    template_values = {'greetings':greetings,"prev":prev,"next":next,"index":index,}
    self.render('template/user/userinfo2.html',template_values)
#    self.render('html/userManage/userInfo.html',template_values)
  @login_required
  def post(self,page):
    searchType = self.request.get('searchType')
    self.redirect('/userInfo?searchType=%s' %searchType)

class UserAdd(PublicPage):
  @login_required
  def get(self):
    url = self.request.url
    template_values = {'url':url,}
    self.render('template/user/userAdd.html',template_values)
#    self.render('html/userManage/userAdd.html',template_values)
  @login_required
  def post(self):
    greeting = User()
    #判断是否存在#
    newUser = self.request.get('username')
    try:
        int(UserName)
        int(self.request.get('password'))
    except :
        self.response.out.write("<script>alert('用户名和密码为数字!');</script>")
        url = self.request.url
        template_values = {'url':url,}
        self.render('template/user/userAdd.html',template_values)
    users = db.GqlQuery("SELECT * FROM User WHERE userName=:1",newUser)
    user = users.fetch(1,0)
    
    if user:
        self.response.out.write("<script>alert('用户名已存在!');</script>")
        url = self.request.url
        template_values = {'url':url,}
        self.render('template/user/userAdd.html',template_values)
    else:
        greeting.userName = newUser
        greeting.passWord = self.request.get('password')
        repassWord = self.request.get('repassword')
        greeting.trueName = self.request.get('truename')
        greeting.tele = self.request.get('telephone')
        greeting.mobile = self.request.get('mobile')
        greeting.put()
        addInitReplay(greeting.userName,greeting.trueName,greeting.tele,greeting.mobile)#默认初始化订阅
        self.redirect('/userInfo')

class UserDelete(PublicPage):
  @login_required
  def get(self):
    userName = self.request.get('userName')
    index = self.request.get('index')
    users = db.GqlQuery("SELECT * FROM User WHERE userName=:1",userName)
    if(users):
      for user in users:
        db.delete(user)
        self.redirect('/userList/%s' %index)

class UserUpdate(PublicPage):
  @login_required
  def get(self):
    userName = self.request.get('userName')
    index = self.request.get('index')
    users = db.GqlQuery("SELECT * FROM User WHERE userName=:1",userName)
    template_values = {'users':users,"index":index,}
    self.render('template/user/userUpdate.html',template_values)
  @login_required
  def post(self):
    userName = self.request.get('username')
    index = self.request.get('index')
    users = db.GqlQuery("SELECT * FROM User WHERE userName=:1",userName)
    if (users):
        for user in users:
            user.trueName = self.request.get('truename')
            user.tele = self.request.get('telephone')
            user.mobile = self.request.get('mobile')
            db.put(user)
            self.redirect('/userList/%s' %index)

class UserPassWordUpdate(PublicPage):
  @login_required
  def get(self):
      userName = self.request.get('userName')
      index = self.request.get('index')
      users = db.GqlQuery("SELECT * FROM User WHERE userName=:1",userName)
      template_values = {'users':users,}
      self.render('template/user/userPasswordUpdate.html',template_values)
#      self.render('html/userManage/userPassWordUpdate.html',template_values)
  @login_required
  def post(self):
      userName = self.request.get('userName')
      oldpassword = self.request.get('oldpassword')
      newpassword = self.request.get('newpassword')
#      renewpassword = self.request.get('renewpassword')
      index = self.request.get('index')
#      if newpassword != renewpassword:
#           self.response.out.write("<script>alert('新密码与确认密码不一致!');</script>")
#           users = db.GqlQuery("SELECT * FROM User WHERE userName=:1",userName)
#           template_values = {'users':users,}
#           self.render('template/user/userPasswordUpdate.html',template_values)
#           return
      users = db.GqlQuery("SELECT * FROM User WHERE userName=:1",userName)
      for user in users:
          if (user.passWord == oldpassword):
              user.passWord = self.request.get('newpassword')
              db.put(user)
          else:
           self.response.out.write("<script>alert('密码错误，无法修改!');</script>")
           users = db.GqlQuery("SELECT * FROM User WHERE userName=:1",userName)
           template_values = {'users':users,}
           self.render('template/user/userPasswordUpdate.html',template_values)
           return
      self.redirect('/userList/%s' %index)
